import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { mconsole } from '../console';
import { isExistFile } from '../util';
import { FilesModel } from '../language/getFileTree';
import { langConfig } from '../language';

const workspaceFolders: any = vscode.workspace.workspaceFolders || [];
const rootPaths = workspaceFolders?.map((val: any) => val.uri.fsPath);
const datas: any = {};

export function rootPathByFile(filePath: string): string {
  if (rootPaths.indexOf(filePath) >= 0) { return filePath; }
  if (isExistFile(path.join(filePath, 'package.json'))) {
    return filePath;
  }
  return rootPathByFile(path.join(filePath, '..'));
}

export function onRelyByFile(filePath: string) {
  const rootPath = rootPathByFile(filePath);
  if (!datas[rootPath]) {
    datas[rootPath] = {
      externals: {},
      files: {},
      tree: {}
    };
    const filesModel = new FilesModel(rootPath);
    datas[rootPath].tree = filesModel.tree;
    datas[rootPath].files = filesModel.files;
    langConfig.parse(datas[rootPath], rootPath);
  }
  return rootPath;
  //  return
}


export function onRelyByRoot() {
  rootPaths.forEach(onRelyByFile);
}


export function onRefresh() {

}

export function getDataByrootPath(rootPath: string) {
  return datas[rootPath] || {};
}